package com.gmscosmo.janus.queue;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gmscosmo.janus.config.JanusConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Base64;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

@Component
public class RabbitmqHttpRequestUtil {
    @Autowired
    JanusConfig janusConfig;

    private String getApiMessage(String queueName) throws Exception {
        //发送一个GET请求
        HttpURLConnection httpConn = null;
        BufferedReader in = null;
        String host = janusConfig.getRabbitmq_host();
        int port = janusConfig.getRabbitmq_port();
        String username = janusConfig.getRabbitmq_username();
        String password = janusConfig.getRabbitmq_password();
        String urlString;
        if (queueName == null) {
            urlString = "http://" + host + ":1" + port + "/api/queues";
        } else {
            urlString = "http://" + host + ":1" + port + "/api/queues/" + "%2F" + "/" + queueName;
        }
        URL url = new URL(urlString);
        httpConn = (HttpURLConnection) url.openConnection();
        //设置用户名密码
        String auth = username + ":" + password;
        Base64.Encoder enc = Base64.getEncoder();
        byte[] encoding = enc.encode(auth.getBytes());
        httpConn.setDoOutput(true);
        httpConn.setRequestProperty("Authorization", "Basic " + new String(encoding));
        // 建立实际的连接
        httpConn.connect();
        //读取响应
        if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
            StringBuilder content = new StringBuilder();
            String tempStr = "";
            in = new BufferedReader(new InputStreamReader(httpConn.getInputStream()));
            while ((tempStr = in.readLine()) != null) {
                content.append(tempStr);
            }
            in.close();
            httpConn.disconnect();
            return content.toString();
        } else {
            httpConn.disconnect();
            return "";
        }
    }

    public List<String> getQueueName(String prefix) {
        String res = null;
        try {
            res = getApiMessage(null);
        } catch (Exception e) {
            return null;
        }
        JSONArray jsonArray = JSONArray.parseArray(res);
        List<String> queues = new ArrayList<>();
        String queue = null;
        for (Object object : jsonArray.toArray()) {
            queue = ((JSONObject) object).getString("name");
            if (queue.startsWith(prefix)) {
                queues.add(queue);
            }
        }
        return queues;
    }

    public String getQueueConsumerHost(String queue) {
        try {
            String res = getApiMessage(queue);
            JSONObject jsonObject = (JSONObject) JSONObject.parse(res);
            JSONArray consumer_details = jsonObject.getJSONArray("consumer_details");
            if(consumer_details==null){
                return null;
            }
            JSONObject channel_details = consumer_details.size()==0?null:consumer_details.getJSONObject(0);
            if(channel_details==null){
                return null;
            }
            channel_details = channel_details.getJSONObject("channel_details");
            String peer_host = channel_details.getString("peer_host");
            return peer_host;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
